// 模拟数据
const mockStocks = [
    { code: '600000', name: '浦发银行', price: 10.25, change: 0.52, open: 10.10, high: 10.30, low: 10.05, volume: 150000 },
    { code: '000001', name: '平安银行', price: 15.30, change: -1.23, open: 15.40, high: 15.45, low: 15.10, volume: 220000 },
    { code: '601318', name: '中国平安', price: 48.75, change: 2.15, open: 48.00, high: 48.90, low: 47.80, volume: 350000 },
    { code: '600519', name: '贵州茅台', price: 1720.50, change: 1.85, open: 1710.00, high: 1725.00, low: 1705.00, volume: 50000 }
];

// 添加股票历史数据
const stockHistoricalData = {
    '600000': generateHistoricalData(10.10, 30),
    '000001': generateHistoricalData(15.40, 30),
    '601318': generateHistoricalData(48.00, 30),
    '600519': generateHistoricalData(1710.00, 30)
};

// 生成历史数据的函数
function generateHistoricalData(startPrice, days) {
    const data = [];
    let currentPrice = startPrice;
    
    for (let i = days; i >= 0; i--) {
        // 生成随机波动
        const changePercent = (Math.random() - 0.5) * 0.04; // 日涨跌幅在-2%到2%之间
        const newPrice = currentPrice * (1 + changePercent);
        
        // 计算最高价和最低价
        const high = Math.max(currentPrice, newPrice) * (1 + Math.random() * 0.01);
        const low = Math.min(currentPrice, newPrice) * (1 - Math.random() * 0.01);
        
        // 成交量
        const volume = Math.floor(Math.random() * 500000) + 100000;
        
        data.push({
            date: new Date(Date.now() - i * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
            open: currentPrice,
            close: newPrice,
            high: high,
            low: low,
            volume: volume
        });
        
        currentPrice = newPrice;
    }
    
    return data;
}

let account = {
    balance: 1000000,
    positions: []
};

// 显示股票详情
function showStockDetail(stockCode) {
    const stock = mockStocks.find(s => s.code === stockCode);
    if (!stock) return;
    
    // 切换到交易页面
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active-nav');
    });
    const tradePageNavItem = document.querySelector('[data-target="trade-page"]');
    if (tradePageNavItem) {
        tradePageNavItem.classList.add('active-nav');
    }
    
    document.querySelectorAll('.page').forEach(page => {
        page.classList.remove('active');
    });
    const tradePage = document.getElementById('trade-page');
    if (tradePage) {
        tradePage.classList.add('active');
    }
    
    // 填充股票代码
    const stockCodeInput = document.getElementById('stock-code');
    if (stockCodeInput) {
        stockCodeInput.value = stockCode;
    }
    
    // 创建K线图详情
    createKLineDetail(stock);
}

// 创建K线图详情
function createKLineDetail(stock) {
    // 查找或创建K线图容器
    let kLineContainer = document.getElementById('k-line-detail-container');
    if (!kLineContainer) {
        kLineContainer = document.createElement('div');
        kLineContainer.id = 'k-line-detail-container';
        kLineContainer.className = 'bg-white rounded-xl shadow-md p-6 mb-6';
        kLineContainer.innerHTML = `
            <h2 class="text-xl font-semibold mb-4">${stock.name} (${stock.code}) K线图</h2>
            <div class="k-line-detail" style="width: 100%; height: 300px; position: relative;">
                <canvas id="k-line-detail-canvas"></canvas>
            </div>
        `;
        
        // 插入到交易表单之前
        const tradeForm = document.getElementById('trade-form');
        if (tradeForm) {
            tradeForm.parentNode.insertBefore(kLineContainer, tradeForm);
        }
    } else {
        // 更新标题
        kLineContainer.querySelector('h2').textContent = `${stock.name} (${stock.code}) K线图`;
    }
    
    // 设置画布大小
    const canvas = document.getElementById('k-line-detail-canvas');
    if (canvas) {
        canvas.width = kLineContainer.querySelector('.k-line-detail').offsetWidth;
        canvas.height = 300;
        drawKLineDetail(canvas, stock);
    }
}

// 绘制K线图详情
function drawKLineDetail(canvas, stock) {
    const ctx = canvas.getContext('2d');
    const width = canvas.width;
    const height = canvas.height;
    
    // 清空画布
    ctx.clearRect(0, 0, width, height);
    
    // 获取股票历史数据
    const historicalData = stockHistoricalData[stock.code] || [];
    
    if (historicalData.length === 0) {
        // 如果没有历史数据，显示错误信息
        ctx.fillStyle = '#666';
        ctx.font = '16px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('暂无历史数据', width/2, height/2);
        return;
    }
    
    // 使用历史数据绘制K线图
    const padding = { top: 20, right: 50, bottom: 30, left: 40 };
    const chartWidth = width - padding.left - padding.right;
    const chartHeight = height - padding.top - padding.bottom;
    
    // 计算价格范围
    let minPrice = Infinity;
    let maxPrice = -Infinity;
    
    historicalData.forEach(day => {
        if (day.low < minPrice) minPrice = day.low;
        if (day.high > maxPrice) maxPrice = day.high;
    });
    
    // 添加一些价格边距
    const pricePadding = (maxPrice - minPrice) * 0.05;
    minPrice -= pricePadding;
    maxPrice += pricePadding;
    
    const priceRange = maxPrice - minPrice;
    
    // 绘制坐标轴
    ctx.beginPath();
    ctx.strokeStyle = '#ccc';
    ctx.lineWidth = 1;
    
    // Y轴
    ctx.moveTo(padding.left, padding.top);
    ctx.lineTo(padding.left, padding.top + chartHeight);
    
    // X轴
    ctx.moveTo(padding.left, padding.top + chartHeight);
    ctx.lineTo(padding.left + chartWidth, padding.top + chartHeight);
    ctx.stroke();
    
    // 绘制网格线和标签
    ctx.fillStyle = '#666';
    ctx.font = '10px Arial';
    ctx.textAlign = 'right';
    
    // Y轴标签和网格线
    const yTicks = 5;
    for (let i = 0; i <= yTicks; i++) {
        const y = padding.top + chartHeight - (i / yTicks) * chartHeight;
        const price = minPrice + (i / yTicks) * priceRange;
        
        // 网格线
        ctx.beginPath();
        ctx.strokeStyle = '#eee';
        ctx.moveTo(padding.left, y);
        ctx.lineTo(padding.left + chartWidth, y);
        ctx.stroke();
        
        // 标签
        ctx.fillText(price.toFixed(2), padding.left - 5, y + 3);
    }
    
    // X轴标签 (显示一周的日期)
    ctx.textAlign = 'center';
    const xTicks = Math.min(historicalData.length, 7); // 最多显示7个日期标签
    for (let i = 0; i < historicalData.length; i += Math.ceil(historicalData.length / xTicks)) {
        const x = padding.left + (i / (historicalData.length - 1)) * chartWidth;
        const date = historicalData[i].date;
        ctx.fillText(date.substring(5), x, padding.top + chartHeight + 15);
    }
    
    // 绘制K线
    const candleWidth = Math.max(1, chartWidth / historicalData.length - 2);
    
    for (let i = 0; i < historicalData.length; i++) {
        const day = historicalData[i];
        const x = padding.left + (i / (historicalData.length - 1)) * chartWidth;
        
        // 计算Y坐标
        const openY = padding.top + chartHeight - ((day.open - minPrice) / priceRange) * chartHeight;
        const closeY = padding.top + chartHeight - ((day.close - minPrice) / priceRange) * chartHeight;
        const highY = padding.top + chartHeight - ((day.high - minPrice) / priceRange) * chartHeight;
        const lowY = padding.top + chartHeight - ((day.low - minPrice) / priceRange) * chartHeight;
        
        // 确定颜色 (收盘价高于开盘价为涨)
        const isUp = day.close >= day.open;
        ctx.fillStyle = isUp ? '#f87171' : '#34d399'; // 红色涨/绿色跌
        ctx.strokeStyle = isUp ? '#f87171' : '#34d399';
        
        // 绘制最高价和最低价的线
        ctx.beginPath();
        ctx.moveTo(x, highY);
        ctx.lineTo(x, lowY);
        ctx.stroke();
        
        // 绘制K线主体
        const topY = Math.min(openY, closeY);
        const bodyHeight = Math.abs(closeY - openY);
        
        if (bodyHeight < 1) {
            // 十字星
            ctx.beginPath();
            ctx.moveTo(x - candleWidth/2, topY);
            ctx.lineTo(x + candleWidth/2, topY);
            ctx.stroke();
        } else {
            // 正常K线
            ctx.fillRect(x - candleWidth/2, topY, candleWidth, bodyHeight);
            ctx.strokeRect(x - candleWidth/2, topY, candleWidth, bodyHeight);
        }
    }
    
    // 添加标题
    ctx.fillStyle = '#333';
    ctx.font = '14px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(`${stock.name} (${stock.code}) 近一个月K线图`, width/2, 15);
}
export function renderMarketTable() {
    const tbody = document.getElementById('market-table');
    tbody.innerHTML = mockStocks.map(stock => `
        <tr class="hover:bg-gray-50">
            <td class="px-6 py-4 whitespace-nowrap font-medium">${stock.code}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stock.name}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stock.price.toFixed(2)}</td>
            <td class="px-6 py-4 whitespace-nowrap ${stock.change >= 0 ? 'text-red-500' : 'text-green-500'}">
                ${stock.change >= 0 ? '+' : ''}${stock.change.toFixed(2)}%
            </td>
        </tr>
    `).join('');
    
    // 为市场动态表格添加折线图组件
    addLineChartComponents();
}

// 添加折线图组件（替代原来的K线图）
function addLineChartComponents() {
    const marketRows = document.querySelectorAll('#market-table tr');
    
    marketRows.forEach((row, index) => {
        if (index === 0) return; // 跳过表头
        
        const stock = mockStocks[index - 1];
        if (!stock) return;
        
        // 创建折线图容器
        const lineChartCell = document.createElement('td');
        lineChartCell.className = 'px-6 py-4 whitespace-nowrap';
        lineChartCell.innerHTML = `
            <div class="line-chart" style="width: 100px; height: 50px; position: relative; cursor: pointer;" data-stock="${stock.code}">
                <canvas class="line-chart-canvas" data-stock="${stock.code}" width="100" height="50"></canvas>
            </div>
        `;
        
        // 插入到涨跌幅列之后
        const changeCell = row.querySelector('td:last-child');
        changeCell.parentNode.insertBefore(lineChartCell, changeCell.nextSibling);
        
        // 添加点击事件
        lineChartCell.addEventListener('click', () => {
            showStockDetail(stock.code);
        });
    });
    
    // 绘制所有折线图
    drawLineCharts();
}

// 绘制折线图
function drawLineCharts() {
    const canvases = document.querySelectorAll('.line-chart-canvas');
    
    canvases.forEach(canvas => {
        const ctx = canvas.getContext('2d');
        const stockCode = canvas.getAttribute('data-stock');
        const stock = mockStocks.find(s => s.code === stockCode);
        const historicalData = stockHistoricalData[stockCode];
        
        if (!stock || !historicalData) return;
        
        const width = canvas.width;
        const height = canvas.height;
        
        // 清空画布
        ctx.clearRect(0, 0, width, height);
        
        // 获取最近30天的收盘价
        const prices = historicalData.map(d => d.close);
        
        // 计算价格范围
        const maxPrice = Math.max(...prices);
        const minPrice = Math.min(...prices);
        const priceRange = maxPrice - minPrice || 0.1; // 防止除零
        
        // 绘制折线图
        ctx.beginPath();
        ctx.strokeStyle = stock.change >= 0 ? '#f87171' : '#34d399'; // 红色涨/绿色跌
        ctx.lineWidth = 2;
        
        for (let i = 0; i < prices.length; i++) {
            const x = (i / (prices.length - 1)) * width;
            const y = height - ((prices[i] - minPrice) / priceRange) * height;
            
            if (i === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        }
        ctx.stroke();
    });
}

export function renderStockTable() {
    const tbody = document.getElementById('stock-table');
    tbody.innerHTML = mockStocks.map(stock => `
        <tr class="hover:bg-gray-50">
            <td class="px-6 py-4 whitespace-nowrap font-medium">${stock.code}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stock.name}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stock.price.toFixed(2)}</td>
            <td class="px-6 py-4 whitespace-nowrap ${stock.change >= 0 ? 'text-red-500' : 'text-green-500'}">
                ${stock.change >= 0 ? '+' : ''}${stock.change.toFixed(2)}%
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <button class="trade-btn px-3 py-1 bg-blue-100 text-blue-600 rounded text-sm" 
                        data-code="${stock.code}">交易</button>
            </td>
        </tr>
    `).join('');
}

export function updateAccountInfo() {
    document.getElementById('available-balance').textContent = account.balance.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });

    // 计算总资产（持仓市值 + 可用资金）
    const positionValue = account.positions.reduce((sum, pos) => {
        const stock = mockStocks.find(s => s.code === pos.code);
        return sum + (stock ? stock.price * pos.amount : 0);
    }, 0);

    const totalAssets = account.balance + positionValue;
    document.getElementById('total-assets').textContent = totalAssets.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });

    // 计算持仓收益
    const positionProfit = account.positions.reduce((sum, pos) => {
        const stock = mockStocks.find(s => s.code === pos.code);
        return sum + (stock ? (stock.price - pos.cost) * pos.amount : 0);
    }, 0);

    const profitElement = document.getElementById('position-profit');
    profitElement.textContent = positionProfit.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
    profitElement.className = positionProfit >= 0 ? 
        'text-2xl font-bold text-red-500' : 
        'text-2xl font-bold text-green-500';
}

export function renderPortfolioTable() {
    const tbody = document.getElementById('portfolio-table');
    if (account.positions.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="px-6 py-4 text-center text-gray-500">
                    暂无持仓
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = account.positions.map(position => {
        const stock = mockStocks.find(s => s.code === position.code);
        const currentPrice = stock ? stock.price : position.cost;
        const profit = (currentPrice - position.cost) * position.amount;
        const profitPercent = ((currentPrice / position.cost) - 1) * 100;
        
        return `
            <tr class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap font-medium">${position.code}</td>
                <td class="px-6 py-4 whitespace-nowrap">${position.name}</td>
                <td class="px-6 py-4 whitespace-nowrap">${position.amount}</td>
                <td class="px-6 py-4 whitespace-nowrap">${position.cost.toFixed(2)}</td>
                <td class="px-6 py-4 whitespace-nowrap">${currentPrice.toFixed(2)}</td>
                <td class="px-6 py-4 whitespace-nowrap ${profit >= 0 ? 'text-red-500' : 'text-green-500'}">
                    ${profit >= 0 ? '+' : ''}${profit.toFixed(2)} (${profitPercent.toFixed(2)}%)
                </td>
            </tr>
        `;
    }).join('');
}

export function executeTrade() {
    const code = document.getElementById('stock-code').value;
    const type = document.getElementById('trade-type').value;
    const priceType = document.getElementById('price-type').value;
    const amount = parseInt(document.getElementById('trade-amount').value);
    const limitPrice = parseFloat(document.getElementById('limit-price').value);

    if (!code || !amount) {
        alert('请填写完整交易信息');
        return;
    }

    const stock = mockStocks.find(s => s.code === code);
    if (!stock) {
        alert('未找到该股票');
        return;
    }

    const price = priceType === 'market' ? stock.price : limitPrice;

    if (type === 'buy') {
        // 买入逻辑
        const cost = price * amount;
        if (cost > account.balance) {
            alert('可用资金不足');
            return;
        }

        account.balance -= cost;
        const existingPos = account.positions.find(p => p.code === code);
        if (existingPos) {
            existingPos.amount += amount;
            existingPos.cost = ((existingPos.cost * existingPos.amount) + cost) / (existingPos.amount + amount);
        } else {
            account.positions.push({
                code,
                name: stock.name,
                amount,
                cost: price,
                buyDate: new Date().toISOString()
            });
        }
    } else {
        // 卖出逻辑
        const position = account.positions.find(p => p.code === code);
        if (!position || position.amount < amount) {
            alert('持仓不足');
            return;
        }

        account.balance += price * amount;
        position.amount -= amount;

        if (position.amount === 0) {
            account.positions = account.positions.filter(p => p.code !== code);
        }
    }

    updateAccountInfo();
    renderPortfolioTable();
    alert(`委托成功：${type === 'buy' ? '买入' : '卖出'} ${stock.name} ${amount}股`);
    document.getElementById('trade-form').reset();
}

